* ****************************
* Recover market fixed effect
* regression on monthly level
******************************

cd "H:\Reduce"
use "H:\Reduce\data.dta", clear
set more off
gen week = month(dofc(time))
gen year = year(dofc(time))
bys productid: gen ptran = _N
keep if ptran>1
replace week = (year - 2014)*12 + week
bys productid week buyercountry: egen pwcquan = sum(quantityinpiece)
duplicates drop productid week buyercountry, force
bys productid: egen entryweek = min(week)
keep productid buyercountry week pwcquan entryweek prevordernum
fillin productid buyercountry
egen pcgroup = group(productid buyercountry)
replace week = 2 if week ==.
xtset pcgroup week
tsfill, full
gsort +pcgroup -productid -buyercountry
by pcgroup: replace productid = productid[1] if productid ==.
by pcgroup: replace buyercountry = buyercountry[1] if buyercountry == ""
bys productid: egen entryweeknew = min(entryweek)
bys productid: egen prevorder = mean(prevordernum)
replace entryweeknew = 2 if prevorder!=0
drop if week<entryweeknew
replace pwcquan = 0 if pwcquan ==.

qui tab buyercountry, gen(countrydum)
egen sellertime = group(productid week)
xtset sellertime
est drop _all
eststo dumfe: xtpoisson pwcquan countrydum*, fe vce(robust)
gen countryefra = .
foreach i of numlist 1/179{
	replace countryefra = _b[countrydum`i'] if countrydum`i'==1
	}
duplicates drop buyercountry, force
keep buyercountry countryefra
save marketfe_feoonly.dta, replace
